﻿using System;
using System.Collections;

namespace ConsoleDemo.InterfaceSegregation
{
    /// <summary>
    /// 实现 IEnumerable 和 IEnumerator 以实现迭代功能
    /// </summary>
    internal class InterfaceDemo2
    {
        public static void Call()
        {
            int[] nums1 = { 1, 2, 3, 4, 5 };
            ArrayList nums2 = new ArrayList { 1, 2, 3, 4, 5 };

            Console.WriteLine(Sum(nums1));
            Console.WriteLine(Sum(nums2));

            var num3 = new ReadOnlyCollection(nums1);
            Console.WriteLine(Sum(num3));


            Student student = new Student { Id = 1 };
            foreach (var item in student)
            {
                Console.WriteLine(item);
            }
        }

        // 调用者绝不多要
        static int Sum(IEnumerable nums)
        {
            int sums = 0;
            foreach (var i in nums)
            {
                sums += (int)i;
            }
            return sums;
        }
    }

    class ReadOnlyCollection : IEnumerable
    {
        private int[] _array;

        public ReadOnlyCollection(int[] array)
        {
            _array = array;
        }

        public IEnumerator GetEnumerator()
        {
            return new Enumerator(this);
        }

        class Enumerator : IEnumerator
        {
            private ReadOnlyCollection _collection;

            private int _head;

            public Enumerator(ReadOnlyCollection collection)
            {
                _collection = collection;
                _head = -1;
            }

            public object Current
            {
                get
                {
                    object o = _collection._array[_head];
                    return o;
                }
            }

            public bool MoveNext()
            {
                return ++_head < _collection._array.Length;
            }

            public void Reset()
            {
                _head = -1;
            }
        }
    }


    // 再写一遍
    class Student : IEnumerable
    {
        public int Id { get; set; }

        string[] student = { "Ant编程1", "Ant编程2", "Ant编程3" };

        public IEnumerator GetEnumerator()
        {
            return new Enumerator(student);
        }

        class Enumerator : IEnumerator
        {
            private string[] _student;
            int _head;

            public Enumerator(string[] student)
            {
                _student = student;
                _head = -1;
            }

            public object Current
            {
                get
                {
                    return _student[_head];
                }
            }

            public bool MoveNext()
            {
                return ++_head < _student.Length;
            }

            public void Reset()
            {
                _head = -1;
            }
        }
    }
}
